package com.ygqh.baby.service.impl;

import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.mp.api.NotifyApi;
import com.foxinmy.weixin4j.mp.message.NotifyMessage;
import com.foxinmy.weixin4j.mp.model.User;
import com.foxinmy.weixin4j.tuple.Text;
import com.ygqh.baby.ao.*;
import com.ygqh.baby.constant.Constant;
import com.ygqh.baby.mapper.YgDrawPrizeHelpMapper;
import com.ygqh.baby.po.YgDrawPrizeHelp;
import com.ygqh.baby.po.YgDrawPrizeHelpExample;
import com.ygqh.baby.po.YgPlatform;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.service.*;
import com.ygqh.baby.utils.ExceptionUtil;
import com.ygqh.baby.utils.ThreadPool;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class YgDrawPrizeHelpServiceImpl implements YgDrawPrizeHelpService {
	protected Logger logger = Logger.getLogger(this.getClass());
	@Autowired
	private YgDrawPrizeHelpMapper ygDrawPrizeHelpMapper;
	@Autowired
	private YgUserService ygUserService;
	@Autowired
	private WxMpAuthorityService wxMpAuthorityService;
	@Autowired
	private YgDrawPrizeService ygDrawPrizeService;
	@Autowired
	private RedisDao redisDao;
	@Autowired
	private ThreadPool threadPool;
	@Value("${default.head.url}")
	private String defaultHeadUrl;
	@Value("${default.nickName.prefix}")
	private String defaultNickNamePrefix;
	@Autowired
	private YgPlatformService ygPlatformService;

	@Override
	public List<YgDrawPrizeHelp> find() {
		YgDrawPrizeHelpExample example = new YgDrawPrizeHelpExample();
		example.createCriteria().andStatusEqualTo(DataStatus.Valid.name());
		return ygDrawPrizeHelpMapper.selectByExample(example);
	}

	@Override
	public int findCount() {
		YgDrawPrizeHelpExample example = new YgDrawPrizeHelpExample();
		example.createCriteria().andStatusEqualTo(DataStatus.Valid.name());
		return ygDrawPrizeHelpMapper.countByExample(example);
	}

	@Override
	public YgDrawPrizeHelp findById(Long id) {
		return ygDrawPrizeHelpMapper.selectByPrimaryKey(id);
	}

	@Override
	public int save(YgDrawPrizeHelp ygDrawPrizeHelp) {
		return ygDrawPrizeHelpMapper.insertSelective(ygDrawPrizeHelp);
	}

	@Override
	public int update(YgDrawPrizeHelp ygDrawPrizeHelp) {
		return ygDrawPrizeHelpMapper.updateByPrimaryKeySelective(ygDrawPrizeHelp);
	}

	@Override
	public ResultSet<YgDrawPrizeHelp> search(QueryInfo queryInfo, String q) {
		List<YgDrawPrizeHelp> list = ygDrawPrizeHelpMapper.selectSuper(queryInfo, q);
		int count = ygDrawPrizeHelpMapper.countSuper(q);
		ResultSet<YgDrawPrizeHelp> resultSet = new ResultSet<YgDrawPrizeHelp>(count, list);
		return resultSet;
	}

	@Override
	public int deleteSoft(Long[] ids) {
		Assert.notEmpty(ids);
		YgDrawPrizeHelpExample example = new YgDrawPrizeHelpExample();
		example.createCriteria().andIdIn(Arrays.asList(ids));
		YgDrawPrizeHelp record = new YgDrawPrizeHelp();
		record.setStatus(DataStatus.Delete);

		return ygDrawPrizeHelpMapper.updateByExampleSelective(record, example);
	}

	@Override
	public int deleteSoft(Long id) {
		return this.deleteSoft(new Long[] { id });
	}

	@Override
	public int saveOrUpdate(YgDrawPrizeHelp ygDrawPrizeHelp) {
		int r = 0;
		if (ygDrawPrizeHelp.getId() != null) {
			r = this.update(ygDrawPrizeHelp);
		} else {
			r = this.save(ygDrawPrizeHelp);
		}
		return r;
	}

	@Override
	public Message addWxHelp(String sourceCode, String openId) {
		if (StringUtils.isNotBlank(sourceCode) && sourceCode.startsWith("DrawPrize-")) {
			String[] split = sourceCode.split("-");
			String source = split[1];
			YgUser ygUser = ygUserService.findByUserName(split[2]);
			if (ygUser == null) {
				return Message.error("不存在该用户，userName=" + split[2] + ";" + sourceCode);
			}
			int count = 1;
			if (!this.hasHelpByOpenId(openId, source, DataStatus.Valid)) {
				User wxUser = null;
				try {

					wxUser = wxMpAuthorityService.getUserInfo(openId);
				} catch (WeixinException e) {
					wxUser = new User();
					wxUser.setNickName(wxUser + "" + openId.substring(0, 4));
					wxUser.setHeadimgurl(defaultHeadUrl);
					logger.warn("获取微信用户信息失败; " + ExceptionUtil.getExceptionMsg(e));
					e.printStackTrace();
				}
				if (wxUser.getHeadimgurl().equals("/0"))
					wxUser.setHeadimgurl(defaultHeadUrl);
				YgDrawPrizeHelp ygDrawPrizeHelp = new YgDrawPrizeHelp(split[1], openId, wxUser.getNickName(),
						wxUser.getHeadimgurl(), ygUser.getId(), count, new Date());
				ygDrawPrizeHelp.setStatus(DataStatus.Valid);
				this.save(ygDrawPrizeHelp);
				ygDrawPrizeService.addCountByHelp(1, source, ygUser.getId(), openId);
				sendHelpSuccessMsg(ygUser.getOpenId(), ygDrawPrizeHelp.getNickName(), split[1]);
				/*return Message.success("您已为 " + ygUser.getNickName()
						+ "助力成功 ，您注册后会加赠您2次机会，中奖机会大大提升，还可挑战好友哦。  <a href='http://m.yiigoo.com/user/login.html?pageBack=http://m.yiigoo.com/promotion/20180314/index.html?sourceCode="
						+ ygUser.getUserName() + "&c=d'>立即注册</a>", sourceCode);*/
				return Message.success("您已为 " + ygUser.getNickName() + "助力成功", sourceCode);
			}
		}
		return Message.error("非助力sourceCode", sourceCode);
	}

	@Override
	public Message addWxHelp(String sourceCode, String openId, DataStatus dataStatus) {
		String source = redisDao.get("DRAW_PRIZE_SOURCE");
		if (DataStatus.Valid.equals(dataStatus)) {
			YgUser ygUser = ygUserService.findBySourceCode(sourceCode);
			if (ygUser == null) {
				return Message.error("不存在该用户，userName=" + sourceCode + ";" + sourceCode);
			}
			YgDrawPrizeHelp help = this.findByOpenId(ygUser.getId(), openId, source, DataStatus.Delete);
			if (help != null) {
				help.setStatus(dataStatus);
				this.update(help);
				ygDrawPrizeService.addCountByHelp(1, source, ygUser.getId(), openId);

				sendHelpSuccessMsg(ygUser.getOpenId(), help.getNickName(), source);
			}

		} else {

			if (StringUtils.isNotBlank(sourceCode) && sourceCode.startsWith("DrawPrize-")) {

				String[] split = sourceCode.split("-");
				YgUser ygUser = ygUserService.findByUserName(split[2]);
				if (ygUser == null) {
					return Message.error("不存在该用户，userName=" + split[2] + ";" + sourceCode);
				}
				int count = 1;
				YgUser user = ygUserService.findByOpenId(openId);

				if (user == null) {

					if (!this.hasHelpByOpenId(openId, source, dataStatus)) {
						User wxUser = null;
						try {
							wxUser = wxMpAuthorityService.getUserInfo(openId);
						} catch (WeixinException e) {
							wxUser = new User();
							wxUser.setNickName(wxUser + "" + openId.substring(0, 4));
							wxUser.setHeadimgurl(defaultHeadUrl);
							logger.warn("获取微信用户信息失败; " + ExceptionUtil.getExceptionMsg(e));
							e.printStackTrace();
						}
						if (wxUser.getHeadimgurl().equals("/0"))
							wxUser.setHeadimgurl(defaultHeadUrl);
						YgDrawPrizeHelp ygDrawPrizeHelp = new YgDrawPrizeHelp(split[1], openId, wxUser.getNickName(), wxUser.getHeadimgurl(), ygUser.getId(),
								count, new Date());
						ygDrawPrizeHelp.setStatus(dataStatus);
						this.save(ygDrawPrizeHelp);
						return Message
								.success(ygUser.getNickName() + " 邀请您助力，您注册助力后会加赠您2次机会，中奖机会大大提升，  <a href='http://m.yiigoo.com/user/login.html?sourceCode="
										+ ygUser.getUserName() + "'>立即注册</a>", sourceCode);
					}
				}
			}
		}
		return Message.error("非助力sourceCode", sourceCode);
	}

	public YgDrawPrizeHelp findByOpenId(Long userId, String openId, String source, DataStatus dataStatus) {
		YgDrawPrizeHelpExample example = new YgDrawPrizeHelpExample();
		example.createCriteria().andUserIdEqualTo(userId).andOpenIdEqualTo(openId).andStatusEqualTo(dataStatus.name());
		example.setOrderByClause("id desc");
		List<YgDrawPrizeHelp> list = ygDrawPrizeHelpMapper.selectByExample(example);
		if (CollectionUtils.isNotEmpty(list)) {
			return list.get(0);
		}
		return null;

	}

	private void sendHelpSuccessMsg(String openId, String nickName, String source) {
		threadPool.getExecutorService().execute(() -> {
			if (StringUtils.isNotBlank(openId)) {
				String content = nickName + " 为您助力成功！";
				if (source.contains(Constant.YIJIADIAN_PLATFORM_NO)) {
					// 来源壹家店小程序
					YgPlatform platform = ygPlatformService.findByPlatformNo(Constant.YIJIADIAN_PLATFORM_NO, AppType.Small);
					content = content + "<a href=\"http://www.qq.com\" data-miniprogram-appid=\"" + platform.getAppId()
							+ "\" data-miniprogram-path=\"pages/activity/20190829/20190829\">立即去抽奖。</a>";
				} else {
					content = content + "<a href='http://m.yiigoo.com/promotion/20190829/index.html'>立即去抽奖。</a>";
				}
				Text text = new Text(content);
				NotifyMessage notifyMessage = new NotifyMessage(openId, text);
				NotifyApi notifyAPI = new NotifyApi(wxMpAuthorityService.findTokenHolder());
				try {
					notifyAPI.sendNotify(notifyMessage);
				} catch (WeixinException e) {
					e.printStackTrace();
				}
			}
		});

	}

	@Override
	public Boolean hasHelpByOpenId(String openId, String source, DataStatus dataStatus) {
		YgDrawPrizeHelpExample example = new YgDrawPrizeHelpExample();
		example.createCriteria().andOpenIdEqualTo(openId).andSourceCodeEqualTo(source).andStatusEqualTo(dataStatus.name());

		int i = ygDrawPrizeHelpMapper.countByExample(example);
		Boolean has = i > 0 ? true : false;

		return has;

	}

	@Override
	public List<YgDrawPrizeHelp> getWxHelpList(QueryInfo queryInfo, Long userId, String sourceCode) {
		return ygDrawPrizeHelpMapper.getWxHelpList(queryInfo, userId, sourceCode);
	}

	@Override
	public int countByUserId(Long userId, String sourceCode) {
		YgDrawPrizeHelpExample example = new YgDrawPrizeHelpExample();
		example.createCriteria().andUserIdEqualTo(userId).andSourceCodeEqualTo(sourceCode).andStatusEqualTo(DataStatus.Valid.name());
		return ygDrawPrizeHelpMapper.countByExample(example);
	}

}
